package net.nagaseyasuhito.nicola.component;

import java.util.Iterator;
import java.util.List;

import net.nagaseyasuhito.nicola.entity.Entry;
import net.nagaseyasuhito.nicola.page.UserPage;
import net.nagaseyasuhito.nicola.service.EntryService;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.DefaultDataProvider;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

import com.google.inject.Inject;

public abstract class EntriesPanel extends Panel {
	@Inject
	protected EntryService entryService;
	
	public EntriesPanel(String id, int maxResults) {
		super(id);

		IDataProvider dataProvider = new DefaultDataProvider() {
			private static final long serialVersionUID = 1L;

			@Override
			public Iterator<Entry> iterator(int first, int count) {
				return EntriesPanel.this.loadEntries(first, count).iterator();
			}

			@Override
			public IModel model(final Object object) {
				//FIXME: 適当実装:p
				return new LoadableDetachableModel() {
					private static final long serialVersionUID = 1L;

					@Override
					protected Object load() {
						return object;
					}
				};
			}

			@Override
			public int size() {
				return (int) EntriesPanel.this.countEntries();
			}
		};
		DataView dataView;
		this.add(dataView = new DataView("entries", dataProvider, maxResults) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(Item item) {
				item.setModel(new CompoundPropertyModel(item.getModelObject()));
				
				Entry entry = (Entry) item.getModelObject();

				PageParameters pageParameters = new PageParameters();
				pageParameters.add("name", entry.getUser().getName());
				item.add(new BookmarkablePageLink("user", UserPage.class, pageParameters).add(new Label("user.name")));
				item.add(new Label("createTimestamp"));
				item.add(new Image("image", new NicolaImageResource(entry.getUser().getImage(), 64)));
				item.add(new Label("content"));
			}
		});
		this.add(new PagingNavigator("navigator", dataView));
		
	}

	public abstract List<Entry> loadEntries(int firstResult, int maxResults);
	public abstract long countEntries();
}